package com.szgd.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.szgd.service.sys.DeptService;
import com.szgd.service.sys.UserService;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


/**
 * CSV文件辅助类
 * @author lish
 *
 */
public class CsvUtil {
	private static Logger logger = Logger.getLogger(CsvUtil.class);
	// 内容分隔符（CSV标准分隔符为英文,）
	private static final char delimiter = ',';
	
	/**
	 * 解析CSV字符串，追加到CSV文件中
	 * @param xml                    待解析的XML字符串
	 * @param childrenCode	                               节点Code
	 * @param childrenAttribute		   节点属性
	 * @param targetFile         CSV文件路径
	 * 注意：解析的xml结构为:
	 *   |<根节点>
	 *   ----|<节点>
	 *   ------|<属性>
	 *   ------|<属性>
	 *   ------|...
	 *   ----|<节点>
	 *   |<根节点>
	 */  
	public static void appendCsvContent(String xml,String childrenCode,String[] childrenAttribute,
			File targetFile){
		boolean writeMark = false;
		try {
			if(!targetFile.exists())
				targetFile.createNewFile();
			
			CsvWriter writer = new CsvWriter(targetFile,
					delimiter,Charset.forName("GBK"));
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			Iterator iter = root.elementIterator(childrenCode);
			String[] values = new String[childrenAttribute.length];
			while(iter.hasNext()){
				writeMark = true;
				Element eleTmp = (Element) iter.next();
				values = new String[childrenAttribute.length];
				for(int x=0;x<childrenAttribute.length;x++){
					values[x] = eleTmp.elementTextTrim(childrenAttribute[x]).replace("\r\n", "").replace("\n","")+" ";
				}
				writer.writeRecord(values);
			}
			if(writeMark)
				writer.flush();
			writer.close();
		} catch (IOException e) {
			logger.error("解析XML后追加到CSV文件IO异常！",e);
		} catch (DocumentException e) {
			logger.error("解析XML后追加到CSV文件Document异常！",e);
		}
		writeMark = false;
	}

	/**
	 * 创建CSV头部
	 * @param headTitle        头部列描述（数组）
	 * @param targetFile	   CSV文件路径
	 */
	public static void createCSVHead(String[] headTitle,File targetFile){
		try {
			if(!targetFile.exists())
				targetFile.createNewFile();
			CsvWriter writer = new CsvWriter(targetFile,
					delimiter,Charset.forName("GBK"));
			String[] values = new String[headTitle.length];
			for(int x=0;x<headTitle.length;x++){
				values[x] =headTitle[x].replace("\r\n", "").replace("\n","");
			}
			writer.writeRecord(values);
			writer.flush();
			writer.close();
		} catch (FileNotFoundException e) {
			logger.error("创建CSV文件头部FileNotFound异常！",e);
		} catch (IOException e) {
			logger.error("创建CSV文件头部IO异常！",e);
		}
	}
	
	/**
	 * 解析CSV文件
	 * @param targetFile
	 */
	public static List<Map<String,Object>> parseCSVFile(File targetFile,String[] columnCode,
			String characterEncoding,int startLine){
		List<Map<String,Object>> returnMap = new ArrayList<Map<String,Object>>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile),characterEncoding));
			CsvReader csvReader = new CsvReader(br);
			int readNumTemp = 1; // 默认开始行为1而不是0
			while(csvReader.readRecord()){
				if(readNumTemp >= startLine){
					// 解析一行数据
					String[] columnDataTmp=csvReader.getValues();
					Map<String,Object> tmpData = new HashMap<String,Object>();
					
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("UnsupportedEncodingException--->",e);
		} catch (FileNotFoundException e) {
			logger.error("FileNotFoundException--->",e);
		} catch (IOException e) {
			logger.error("IOException--->",e);
		}
		return returnMap;
	}
	
	/**
	 * 插入同步用户信息（临时用。。。）
	 * @param targetFile
	 * @param characterEncoding
	 * @param startLine
	 * @return
	 */
	public static List<Map<String,Object>> parseCSVFile2(File targetFile,
			String characterEncoding,int startLine){
		List<Map<String,Object>> returnMap = new ArrayList<Map<String,Object>>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile),characterEncoding));
			CsvReader csvReader = new CsvReader(br);
			int readNumTemp = 1; // 默认开始行为1而不是0
			while(csvReader.readRecord()){
				if(readNumTemp >= startLine){
					// 解析一行数据
					String[] columnDataTmp=csvReader.getValues();
					Map<String,Object> tmpData = new HashMap<String,Object>();
					tmpData.put("USER_ID", columnDataTmp[0]);
					tmpData.put("CA_CARD", columnDataTmp[1]);
					tmpData.put("USER_CA", columnDataTmp[2]);
					tmpData.put("LOGIN_ID", columnDataTmp[3]);
					tmpData.put("USER_PWD", columnDataTmp[4]);
					tmpData.put("USER_NAME", columnDataTmp[5]);
					tmpData.put("DEPT_CD", columnDataTmp[6]);
					tmpData.put("IDENTITY_NO", columnDataTmp[7]);
					tmpData.put("DUTY_CD", columnDataTmp[8]);
					tmpData.put("DUTY_NAME", columnDataTmp[9]);
					tmpData.put("PC_NAME", columnDataTmp[11]);
					tmpData.put("PC_IP", columnDataTmp[12]);
					tmpData.put("EMAIL", columnDataTmp[13]);
					tmpData.put("EMAIL_PWD", columnDataTmp[14]);
					tmpData.put("PUBLIC_TEL", columnDataTmp[15]);
					tmpData.put("MOBILE", columnDataTmp[16]);
					tmpData.put("OPERATE_STATUS", columnDataTmp[17]);
					tmpData.put("PUB_FLAG", columnDataTmp[18]);
					tmpData.put("SORT_NUMBER", columnDataTmp[19]);
					tmpData.put("User_Source", "UC");
					returnMap.add(tmpData);
				}
				readNumTemp++;
			}
			if(returnMap.size()>0){
				UserService userService = (UserService) SpringUtil.getBean("userService");
				userService.batchInsertUser(returnMap);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnMap;
	}
	
	
	/**
	 * 插入同步用户信息（正式用。。。）
	 * @param targetFile
	 * @param characterEncoding
	 * @param startLine
	 * @return
	 */
	public static String parseCSVFile2A(File targetFile,
			String characterEncoding,int startLine){
		List<Map<String,Object>> returnMap = new ArrayList<Map<String,Object>>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile),characterEncoding));
			CsvReader csvReader = new CsvReader(br);
			int readNumTemp = 1; // 默认开始行为1而不是0
			while(csvReader.readRecord()){
				if(readNumTemp >= startLine){
					// 解析一行数据
					String[] columnDataTmp=csvReader.getValues();
					Map<String,Object> tmpData = new HashMap<String,Object>();
					tmpData.put("USER_ID", columnDataTmp[0].toString().trim());
					tmpData.put("CA_CARD", columnDataTmp[1].toString().trim());
					tmpData.put("USER_CA", columnDataTmp[2].toString().trim());
					tmpData.put("LOGIN_ID", columnDataTmp[3].toString().trim());
					//tmpData.put("USER_PWD", columnDataTmp[4]);
					tmpData.put("USER_PWD", AEncryptHelper.encrypt(AEncryptHelper.defaultPass, columnDataTmp[3].toString().trim()));
					tmpData.put("USER_NAME", columnDataTmp[5].toString().trim());
					tmpData.put("DEPT_CD", columnDataTmp[6].toString().trim());
					String identityNo = columnDataTmp[7].toString().toString().trim();
					tmpData.put("IDENTITY_NO", identityNo);
					tmpData.put("DUTY_CD", columnDataTmp[8].toString().trim());
					tmpData.put("DUTY_NAME", columnDataTmp[9].toString().trim());
					tmpData.put("PC_NAME", columnDataTmp[11].toString().trim());
					tmpData.put("PC_IP", columnDataTmp[12].toString().trim());
					tmpData.put("EMAIL", columnDataTmp[13].toString().trim());
					tmpData.put("EMAIL_PWD", columnDataTmp[14].toString().trim());
					tmpData.put("PUBLIC_TEL", columnDataTmp[15].toString().trim());
					tmpData.put("MOBILE", columnDataTmp[16].toString().trim());
					tmpData.put("OPERATE_STATUS", columnDataTmp[17].toString().trim());
					tmpData.put("PUB_FLAG", columnDataTmp[18].toString().trim());
					tmpData.put("SORT_NUMBER", columnDataTmp[19].toString().trim());
					tmpData.put("User_Source", "UC");
					returnMap.add(tmpData);
				}
				readNumTemp++;
			}
			if(returnMap.size()>0){
				UserService userService = (UserService) SpringUtil.getBean("userService");
				userService.batchInsertUser(returnMap);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "0";
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "0";
		} catch (IOException e) {
			e.printStackTrace();
			return "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}
	
	/**
	 * 插入同步机构信息（临时用。。。）
	 * @param targetFile
	 * @param characterEncoding
	 * @param startLine
	 * @return
	 */
	public static List<Map<String,Object>> parseCSVFile3(File targetFile,
			String characterEncoding,int startLine){
		List<Map<String,Object>> returnMap = new ArrayList<Map<String,Object>>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile),characterEncoding));
			CsvReader csvReader = new CsvReader(br);
			int readNumTemp = 1; // 默认开始行为1而不是0
			while(csvReader.readRecord()){
				if(readNumTemp >= startLine){
					// 解析一行数据
					String[] columnDataTmp=csvReader.getValues();
					Map<String,Object> tmpData = new HashMap<String,Object>();
					tmpData.put("DEPT_ID", columnDataTmp[0].toString().trim());
					tmpData.put("DEPT_CD", columnDataTmp[1].toString().trim());
					tmpData.put("DEPT_NAME", columnDataTmp[2].toString().trim());
					tmpData.put("DEPT_SHORT_NAME", columnDataTmp[3].toString().trim());
					tmpData.put("SORT_NUMBER", columnDataTmp[4].toString().trim());
					tmpData.put("DEPT_PARENT_ID", columnDataTmp[5].toString().trim());
					tmpData.put("Address", columnDataTmp[6].toString().trim());
					tmpData.put("POST_AI_CODE", columnDataTmp[7].toString().trim());
					tmpData.put("OPERATE_STATUS", columnDataTmp[8].toString().trim());
					tmpData.put("PUB_FLAG", columnDataTmp[9].toString().trim());
					tmpData.put("CITY_CODE", columnDataTmp[11].toString().trim());
					
					returnMap.add(tmpData);
				}
				readNumTemp++;
			}
			if(returnMap.size()>0){
				DeptService deptService = (DeptService) SpringUtil.getBean("deptService");
				deptService.batchInsertDept(returnMap);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnMap;
	}
	
	
	/**
	 * 插入同步机构信息（临时用。。。）
	 * @param targetFile
	 * @param characterEncoding
	 * @param startLine
	 * @return
	 */
	public static String parseCSVFile3A(File targetFile,
			String characterEncoding,int startLine){
		List<Map<String,Object>> returnMap = new ArrayList<Map<String,Object>>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile),characterEncoding));
			CsvReader csvReader = new CsvReader(br);
			int readNumTemp = 1; // 默认开始行为1而不是0
			while(csvReader.readRecord()){
				if(readNumTemp >= startLine){
					// 解析一行数据
					String[] columnDataTmp=csvReader.getValues();
					Map<String,Object> tmpData = new HashMap<String,Object>();
					tmpData.put("DEPT_ID", columnDataTmp[0].toString().trim());
					tmpData.put("DEPT_CD", columnDataTmp[1].toString().trim());
					tmpData.put("DEPT_NAME", columnDataTmp[2].toString().trim());
					tmpData.put("DEPT_SHORT_NAME", columnDataTmp[3].toString().trim());
					tmpData.put("SORT_NUMBER", columnDataTmp[4].toString().trim());
					tmpData.put("DEPT_PARENT_ID", columnDataTmp[5].toString().trim());
					tmpData.put("Address", columnDataTmp[6].toString().trim());
					tmpData.put("POST_AI_CODE", columnDataTmp[7].toString().trim());
					tmpData.put("OPERATE_STATUS", columnDataTmp[8].toString().trim());
					tmpData.put("PUB_FLAG", columnDataTmp[9].toString().trim());
					tmpData.put("CITY_CODE", columnDataTmp[11].toString().trim());
					
					returnMap.add(tmpData);
				}
				readNumTemp++;
			}
			if(returnMap.size()>0){
				DeptService deptService = (DeptService) SpringUtil.getBean("deptService");
				deptService.batchInsertDept(returnMap);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "0";
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "0";
		} catch (IOException e) {
			e.printStackTrace();
			return "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}
	public static void main(String[] args) throws DocumentException {
		//导入用户
		File targetFile = new File("D:/dataUpate/user20160919154911.csv");
		parseCSVFile2A(targetFile,"GBK",2);
		System.out.println("11111111111");
		//导入机构
		//File targetFile2 = new File("D:/dataUpate/dept20160919154911.csv");
		//parseCSVFile3A(targetFile2,"GBK",1);
		//System.out.println("2222222222");
	}

}
